package com.yunshipei.core.manager;

import com.yunshipei.core.ui.TabFragment;

import java.util.ArrayList;
import java.util.List;

public final class TabManager {

    private List<TabFragment> mTabList = new ArrayList<>();

    private static final class TabManagerInner {
        private static final TabManager instances = new TabManager();
    }

    private TabManager() {
    }

    public static TabManager getInstance() {
        return TabManagerInner.instances;
    }

    public void addView(TabFragment fragment) {
        if (mTabList.size() >= getMax()) {
            removeView(0);
        }
        mTabList.add(fragment);
    }

    public void removeView(TabFragment fragment) {
        mTabList.remove(fragment);
        fragment.release();
    }

    /**
     * 移除position的tab，将会返回list中的下一个有效的tab的position
     * 如果返回-1，则说明list中没有tab了
     *
     * @param pos 移除的tab的position
     * @return 下一个有效的tab的position
     */
    public int removeView(int pos) {
        removeView(getFragment(pos));
        int size = getSize();
        if (size == 0) return -1;
        if (size == 1) return 0;
        if (pos == 0) return 0;
        if (pos == size) return (size - 1);
        return pos;
    }

    public TabFragment getFragment(int i) {
        return mTabList.size() == 0 || i >= getSize() || i < 0 ? null : mTabList.get(i);
    }

    public int getSize() {
        return mTabList.size();
    }

    public void removeAllViews() {
        while (mTabList.size() > 0) {
            removeView(0);
        }
    }

    private int getMax() {
        int max = 5;
        if (android.os.Build.BRAND.equalsIgnoreCase("xiaomi")) {
            max = 2;
        } else if ("GT-I9500".equals(android.os.Build.MODEL)) {
            max = 1;
        }
        return max;
    }

    public int getTabPosition(String url) {
        for (int i = 0; i < mTabList.size(); i++) {
            TabFragment tabFragment = mTabList.get(i);
            String homURL = tabFragment.getStartURL();
            if (homURL.equals(url)) {
                return i;
            }
        }
        return -1;
    }

    public TabFragment getTabFragment(String url) {
        for (TabFragment tabFragment : mTabList) {
            if (url.equals(tabFragment.getStartURL())) {
                return tabFragment;
            }
        }
        return null;
    }

    public void destroy() {
        removeAllViews();
    }
}
